package edu.ncsu.csc.ip.routing.dv;

import java.util.Map;

/**
 * Class <code>SenderThread</code>
 * 
 * SenderThread send new DV to all neighbors. It waits on it's local Neighbor DV
 * queue if no new DV is available.
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */
public final class SenderThread implements Runnable {

	final RouterLocal router;

	public SenderThread(RouterLocal router) {
		this.router = router;

	}

	public void run() {
		try {
			while (true) {

				// Wait until a new DV is produced by neighbors then
				// calculate the new local DV if changed send it to all
				Map<Node, RouteEntity> newDvMap;
				if ((newDvMap = router
						.calculateNewDV(router.updatedNeighborDvQueue.take())) != null) {
					router.localNode.distanceVector = newDvMap;
					router.incrementIteration();

					// send new DV to all other neighbors
					for (RouteEntity re : router.localNode.neighborsMap
							.values()) {
						re.nextNode.router.updatedNeighborDvQueue
								.add(router.localNode.clone());
					
						router.incrementUpdatesSent();
						re.nextNode.router.incrementUpdatesReceived();
					}
				}
			}
		} catch (InterruptedException ex) {
			System.out.println("InterruptedException: " + ex.getMessage());
		}
	}

}
